package com.maint.m

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import androidx.core.content.ContextCompat
import com.pedro.rtmp.utils.ConnectCheckerRtmp
import com.pedro.rtplibrary.rtmp.RtmpCamera1
import com.pedro.rtplibrary.view.OpenGlView

class StreamManager(private val context: Context, private val openGlView: OpenGlView) {

    private var rtmpCamera1: RtmpCamera1? = null
    private var isStreaming = false
    private var streamCallback: StreamCallback? = null
    private var isCameraInitialized = false
    private var isSurfaceReady = false

    init {
        setupSurfaceCallback()
    }

    private fun setupSurfaceCallback() {
        openGlView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d("StreamManager", "Surface created")
                isSurfaceReady = false // 先设为false，等待surfaceChanged确认
                // Surface创建后立即初始化摄像头
                initRtmpCameraIfNeeded()
            }

            override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
                Log.d("StreamManager", "Surface changed: $width x $height")
                // 只有在surfaceChanged中才真正标记为就绪，确保Surface已完全初始化
                isSurfaceReady = true
                // 通知上层Surface已就绪
                streamCallback?.onSurfaceReady()
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                Log.d("StreamManager", "Surface destroyed")
                isSurfaceReady = false
                if (isStreaming) {
                    stopStreaming()
                }
            }
        })
    }

    private fun initRtmpCameraIfNeeded() {
        if (!isCameraInitialized && isSurfaceReady) {
            try {
                rtmpCamera1 = RtmpCamera1(openGlView, object : ConnectCheckerRtmp {
                    override fun onConnectionStartedRtmp(rtmpUrl: String) {
                        Log.d("RTMP", "连接开始: $rtmpUrl")
                        streamCallback?.onConnectionStarted()
                    }

                    override fun onConnectionSuccessRtmp() {
                        streamCallback?.onConnectionSuccess()
                    }

                    override fun onConnectionFailedRtmp(reason: String) {
                        isStreaming = false
                        // 确保在UI线程中修改视图
                        openGlView.post {
                            openGlView.visibility = View.GONE
                        }
                        Log.e("RTMP", "连接失败: $reason")
                        streamCallback?.onConnectionFailed(reason)
                    }

                    override fun onNewBitrateRtmp(bitrate: Long) {
                        Log.d("RTMP", "新比特率: $bitrate")
                    }

                    override fun onDisconnectRtmp() {
                        isStreaming = false
                        // 确保在UI线程中修改视图
                        openGlView.post {
                            openGlView.visibility = View.GONE
                        }
                        Log.d("RTMP", "连接断开")
                        streamCallback?.onDisconnected()
                    }

                    override fun onAuthErrorRtmp() {
                        Log.e("RTMP", "认证错误")
                        streamCallback?.onAuthError()
                    }

                    override fun onAuthSuccessRtmp() {
                        Log.d("RTMP", "认证成功")
                        streamCallback?.onAuthSuccess()
                    }
                })
                isCameraInitialized = true
            } catch (e: Exception) {
                Log.e("StreamManager", "初始化摄像头失败", e)
                streamCallback?.onStreamStartError("初始化摄像头失败: ${e.message}")
            }
        }
    }

    fun startStreaming(rtmpUrl: String): Boolean {
        if (!checkPermissions()) {
            streamCallback?.onPermissionDenied()
            return false
        }

        // 强化Surface状态检查：确保Surface已创建且有效
        if (!isSurfaceReady || openGlView.holder.surface == null || !openGlView.holder.surface.isValid) {
            streamCallback?.onStreamStartError("Surface未准备就绪（无效或未创建）")
            return false
        }

        if (!isStreaming && isSurfaceReady) {
            try {
                // 确保摄像头已初始化
                initRtmpCameraIfNeeded()

                rtmpCamera1?.let { camera ->
                    openGlView.visibility = View.VISIBLE

                    if (camera.prepareAudio() && camera.prepareVideo()) {
                        camera.startStream(rtmpUrl)
                        isStreaming = true
                        streamCallback?.onStreamStarted()
                        return true
                    } else {
                        openGlView.visibility = View.GONE
                        streamCallback?.onStreamPrepareFailed()
                        return false
                    }
                } ?: run {
                    streamCallback?.onStreamStartError("摄像头未初始化")
                    return false
                }
            } catch (e: Exception) {
                openGlView.visibility = View.GONE
                streamCallback?.onStreamStartError(e.message ?: "未知错误")
                Log.e("StreamManager", "启动推流失败", e)
                return false
            }
        } else if (!isSurfaceReady) {
            streamCallback?.onStreamStartError("Surface未准备就绪")
            return false
        }
        return false
    }

    fun stopStreaming() {
        if (isStreaming && isCameraInitialized) {
            try {
                rtmpCamera1?.stopStream()
                isStreaming = false
                openGlView.visibility = View.GONE
                streamCallback?.onStreamStopped()
            } catch (e: Exception) {
                Log.e("StreamManager", "停止推流失败", e)
            }
        }
    }

    fun isStreaming(): Boolean = isStreaming

    fun setStreamCallback(callback: StreamCallback) {
        this.streamCallback = callback
    }

    private fun checkPermissions(): Boolean {
        val permissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )

        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    fun onDestroy() {
        if (isStreaming) {
            try {
                stopStreaming()
            } catch (e: Exception) {
                Log.e("StreamManager", "停止推流失败", e)
            }
        }
        isCameraInitialized = false
        try {
            rtmpCamera1?.stopPreview()
        } catch (e: Exception) {
            Log.e("StreamManager", "停止预览失败", e)
        }
        rtmpCamera1 = null
    }

    interface StreamCallback {
        fun onConnectionStarted() {}
        fun onConnectionSuccess() {}
        fun onConnectionFailed(reason: String) {}
        fun onDisconnected() {}
        fun onAuthError() {}
        fun onAuthSuccess() {}
        fun onStreamStarted() {}
        fun onStreamStopped() {}
        fun onStreamStartError(error: String) {}
        fun onStreamPrepareFailed() {}
        fun onPermissionDenied() {}
        fun onSurfaceReady() {}
    }
}
